package common.server.respcode;

import common.server.entity.InsideResponseMessage;
import common.server.entity.Message;
import common.server.entity.OutsideResponseMessage;
import common.server.exception.BaseException;

/**
 * 响应帮助类
 * 
 * @author Administrator
 * @version [版本号, 2018/1/5 0005]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public final class RespHelper {

	/**
	 * 构建外部请求响应
	 * 
	 * @param respCode
	 * @param data
	 * @param <T>
	 * @return
	 */
	public static <T> OutsideResponseMessage<T> buildOutsideRespMessage(
			RespCode respCode, T data) {
		return new OutsideResponseMessage().setRetCode(respCode.getCode())
				.setRetDesc(respCode.getDesc()).setRspBody(data);
	}

	/**
	 * 构建内部请求响应
	 * 
	 * @param respCode
	 * @param data
	 * @param <T>
	 * @return
	 */
	public static <T> InsideResponseMessage<T> buildInsideRespMessage(
			RespCode respCode, T data) {
		return new InsideResponseMessage().setRetCode(respCode.getCode())
				.setRetDesc(respCode.getDesc()).setRspBody(data);
	}

	/**
	 * 根据异常构建请求
	 * 
	 * @param exception
	 * @param <T>
	 * @return
	 */
	public static <T> InsideResponseMessage<T> buildInsideRespMessage(
			BaseException exception) {
		RespCode code = exception.isRetCode() ? exception.getRespCode()
				: RespCodeService.COMM_ERROR;
		return new InsideResponseMessage().setRetCode(code.getCode())
				.setRetDesc(code.getDesc());
	}

	/**
	 * 根据异常构建请求
	 * 
	 * @param exception
	 * @param <T>
	 * @return
	 */
	public static <T> OutsideResponseMessage<T> buildOutsideRespMessage(
			BaseException exception) {
        RespCode code = exception.isRetCode() ? exception.getRespCode()
                : RespCodeService.COMM_ERROR;
        return new OutsideResponseMessage().setRetCode(code.getCode())
                .setRetDesc(code.getDesc());
	}

	/**
	 * 是否为成功响应
	 * 
	 * @param responseMessage
	 * @return
	 */
	public static boolean isSuccessResp(Message responseMessage) {
		String code = "";
		if (responseMessage instanceof OutsideResponseMessage) {
			code = ((OutsideResponseMessage) responseMessage).getRetCode();
		}
		if (responseMessage instanceof InsideResponseMessage) {
			code = ((InsideResponseMessage) responseMessage).getRetCode();
		}
		return RespCodeService.SUCCESS.getCode().equals(code);
	}

}
